#! /usr/bin/perl -w
use strict;



#
#
#
#       Filename:   ChangeEmptyDF
#       Function:   Change the given fields from integer to character 
#                   in mfgempty.df. And generate new file as mfgempty.df.out 
#       Input:      1.db_field (Format:db name,field name)
#                   2.mfgempty.df
#                   eg: ./ChangeEmptyDF
#       Output:     mfgempty.df.out 
#
#
sub ModifyLineWithDBField();

our $emptydbName = "mfgempty.df";
our $dbFieldName = "db_field";
our @lines;
our $lineNbr=0;
our $lineMax=0;
$/= "ADD";

open ( DFFILE, "$emptydbName")|| die "Can not open $emptydbName\n";
open ( OUTFILE, ">$emptydbName.out");
@lines= <DFFILE>;
$lineMax = @lines;
$/="\n";
my @fields = `grep '.*' $dbFieldName | sort | uniq`;

foreach (@fields)
{
    if ( $_ =~ /([^,]+),([^,]+)/ )
    {
        &ModifyLineWithDBField($1,$2);
    }
}

#The left lines
while($lineNbr < $lineMax)
{
    print OUTFILE "$lines[$lineNbr]";
    $lineNbr++;
}

sub ModifyLineWithDBField()
{
    my $dbName = $_[0];
    my $fieldName = $_[1];
    chomp($fieldName);
    while( $lines[$lineNbr] !~ /FIELD \"$fieldName\" OF \"$dbName\"/)
    {
       print OUTFILE "$lines[$lineNbr]";
       $lineNbr++;
       if ( $lineNbr >= $lineMax)
       {
           print "OverFlow\n";
           exit;
       }
    
    }
    $lines[$lineNbr] =~ s/AS integer/AS character/g;
    $lines[$lineNbr] =~ s/FORMAT ".*"/FORMAT "x(10)"/g;
    $lines[$lineNbr] =~ s/INITIAL ".*"/INITIAL ""/g;
    $lines[$lineNbr] =~ s/MAX-WIDTH [0-9]+/MAX-WIDTH 38/g;
    print OUTFILE "$lines[$lineNbr]";
    $lineNbr++;
}
